using System;
using System.Web.Mvc;

using Azure.Membership;
using Azure.Infrastructure;
using StructureMap;
using StructureMap.Configuration.DSL;

namespace Azure.Web.Configuration
{
    public static class Container
    {
        private static IContainer _container;
        private static readonly Object LockObject = new object();

        public static IContainer RunAs<T>() where T : Registry, new()
        {
            _container = _container.RunIfNotSet(LockObject, () => new StructureMap.Container(new T()));

            return _container;
        }

        public static void Reset()
        {
            _container = null;
        }

        public static IContainer Setup(ControllerBuilder controllerBuilder)
        {
            AzureMembershipProvider.LoadRepository = _container.GetInstance<IMembershipRepository>;
            controllerBuilder.SetControllerFactory(new StructureMapControllerFactory(_container));

            return _container;
        }

        public class StructureMapControllerFactory : DefaultControllerFactory
        {
            private readonly IContainer _container;

            public StructureMapControllerFactory(IContainer container)
            {
                _container = container;
            }

            protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
            {
                IController result;

                try
                {
                    result = (IController)_container.GetInstance(controllerType);
                }
                catch (Exception)
                {
                    return base.GetControllerInstance(requestContext, controllerType);
                }

                return result;
            }
        }
    }
}